<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 会员类
 * @package  module/base/customer
 * @author   allen.qiang
 * @version 1.0
 */

class quanliCust {


    /**
     * 创建会员购买记录
     * 收货地址->默认收货地址
     */
    public function buy_log_array( $pcustID ){

        //加载会员收货地址类
        quanli_require('module/base/customer/custDeliver.class.php');

        //实例会员收货地址类
        $custDeliver = new custDeliver();

        $buy_log_array = array(

            'pcustID' => $pcustID,

            'deliverID' => null,

            'send_region_id' => null,

            'send_time_id' => null,

            'payTypeID' => null,

            'pay_type' => null,

            'payment_method_id' => null,

            'invoiceID' => null,
        );

        $deliver = $custDeliver->getDefaultAddress( $pcustID );

        if($deliver){
            $buy_log_array['deliverID'] = $deliver;
        }

        return $buy_log_array;

    }

    /**
     * 查询会员资料
     * @param array $arg_array 查询参数数组
     * @return null|array
     */
    public function getCustomerInfo( &$arg_array ) {
        
        global $G_SHOP;

        //sql字符串
        $sql = '';

        //SQL字段类型字符串
        $params_type = '';

        //SQL字段值数组
        $params_array = array();

        //客户号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //用户名
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['custID'];
        }

        //手机号码
        if (isset($arg_array['mobile']) && !empty($arg_array['mobile'])) {
            $sql .= ' AND mobile = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['mobile']);
        }

        //电话号码
        if (isset($arg_array['phone']) && !empty($arg_array['phone'])) {
            $sql .= ' AND phone LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['phone']) . '%';
        }

        //email
        if (isset($arg_array['email']) && !empty($arg_array['email'])) {
            $sql .= ' AND email = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['email']);
        }

        //用户姓名
        if (isset($arg_array['custname']) && !empty($arg_array['custname'])) {
            $sql .= ' AND custname LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['custname']) . '%';
        }

        //会员类型
        if ( isset($arg_array['customerType']) && !empty($arg_array['customerType']) ) {
            $sql .= ' AND customerType = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['customerType'];
        }

        //会员等级
        if ( isset($arg_array['rankID']) && !empty($arg_array['rankID']) ) {
            $sql .= ' AND rankID = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['rankID'];
        }

        //电话
        if ( isset($arg_array['phone']) && !empty($arg_array['phone']) ) {
            $sql .= ' AND phone = ? ';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['phone']);
        }

        //邮箱
        if ( isset($arg_array['email']) && !empty($arg_array['email']) ) {
            $sql .= ' AND email = ? ';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['email']);
        }

        if (isset($arg_array['timeStamp']) && !empty($arg_array['timeStamp'])) {
            $sql .= ' AND  timeStamp > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['timeStamp'];
        }

        //注册时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND  createTime >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }

        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND  createTime <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        if (isset($arg_array['rp'])) {

            //统计数量
            $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_master ' . $sql;
            $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            $item_count = $count_array[0]->item_count;
            if ($item_count == 0) {
                $arg_array['count'] = 0;
                return null;
            }

            $arg_array['count'] = $item_count;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //分页
            if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                $arg_array['page'] = 1;

            $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        } else {

            if (empty($sql)) {
                return null;
            }

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname'])) {
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
            }

        }


        //查询分类信息
        $search_sql = 'SELECT * FROM cust_master ' . $sql;
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array)
            return null;

        $item_array = array();

        foreach ($temp_item_array as &$item) {

            //用户信息数组
            $item_array[]  = array(
                'uuid'	    => 	$item->uuid,
                'timeStamp'	=>	$item->timeStamp,
                'creator' 	=> 	$item->creator,
                'createTime' => $item->createTime,
                'editor'	=> 	$item->editor,
                'custID'	=> 	$item->custID,
                'pcustID'	=> 	$item->pcustID,
                'rankID'	=> 	$item->rankID,
                'rankName'	=>	$item->rankName,
                'pwd'		=> 	$item->pwd,
                'custname'=>	decryptD($item->custname),
                'sexy'	=>	$item->sexy,
                'birthday'	=> 	$item->birthday == '0000-00-00' ? '' : $item->birthday,
                'QQ'	=> 	$item->QQ,
                'MSN'	=>	$item->MSN,
                'email'	=>	decryptD($item->email),
                'mobile'	=>	decryptD($item->mobile),
                'phone'	=>	decryptD($item->phone),
                'useFlg'	=>	$item->useFlg,
                'useName'	=>	$item->useFlg ? '启用' : '禁用',
                'head_pic'	=>	$item->head_pic,
                'head_pic_link'	=>	$item->head_pic ? G_IMAGE_URL .$item->head_pic : '',
                'custSource'	=>	$item->custSource,
                'custSourceName'	=>	$GLOBALS['cust_source'][$item->custSource],
                'custType'	=>	$item->custType,
                'custTypeName'	=>	$GLOBALS['cust_type'][$item->custType],
                'unionName'	=>	$item->unionName,
                'sumAmt'	=>	$item->sumAmt,
                'nickName' => $item->nickName,
                'recom_pcustID' => $item->recom_pcustID,
                'provinceid' => $item->provinceid,
                'provinceName' => $item->provinceName,
                'cityid' => $item->cityid,
                'cityName' => $item->cityName,
                'countyid' => $item->countyid,
                'countyName' => $item->countyName,
                'address' => decryptD($item->address),
                'identityCard' => decryptD($item->identityCard),
                'maritalStatus' => $item->maritalStatus,
                'monthlyIncome' => $item->monthlyIncome,
                'isMobileVerify' => $item->isMobileVerify,
                'frist_bill_time' => $item->frist_bill_time,
                'last_bill_time' => $item->last_bill_time,
            );
        }

        return $item_array;

    }


    /**
     * 查询会员信息
     * @param array $arg_array 查询参数数组
     * @return null|array
     */
    public function searchCustomerInfo( &$arg_array ) {
        return $this->getCustomerInfo( $arg_array );
    }

    /**
     * 查询会员详情
     * @param array $arg_array 查询参数数组
     * @return null|array
     */
    public function searchCustomerDetail( $arg_array ) {

        $flg = 0;
        if (isset($arg_array['pcustID']) && quanli_is_int($arg_array['pcustID'])) {
            $flg = 1;
        }
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $flg = 1;
        }
        if ($flg == 0) {
            return null;
        }

        $customer_array = $this->searchCustomerInfo( $arg_array );
        if (!$customer_array) {
            return null;
        }

        return $customer_array[0];

    }

    /**
     * 注册会员
     * @param $arg_array
     * @return array
     */
    public function register( $arg_array ) {

        global $G_SHOP;

        //加载类文件
        quanli_include('module/base/customer/custRank.class.php');

        //实例会员等级类
        $custRank = new custRank();

        //检查参数
        if (!isset($arg_array['custID'], $arg_array['pwd'], $arg_array['custType'], $arg_array['custSource'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!in_array($arg_array['custType'], array(1, 2, 3))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!in_array($arg_array['custSource'], array(1, 2, 3, 4, 5, 6, 7))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if ($arg_array['custSource'] != 7) {
            if (!is_mobile($arg_array['custID'])) {
                return array( 'code' => 400, 'message' => '请输入手机号码' );
            }
        }

        if (!is_pwd($arg_array['pwd'])) {
            return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字' );
        }

        if ($arg_array['custSource'] == 7) {
            $custID = $arg_array['custID'];
            $mobile = '';
        } else {
            $custID = $mobile = $arg_array['custID'];
        }

        $pwd = $arg_array['pwd'];

        //第三方登录会员名
        $unionName = isset($arg_array['unionName']) ? trim($arg_array['unionName']) : null;

        //会员昵称
        $nickName = isset($arg_array['nickName']) ? trim($arg_array['nickName']) : $custID;

        //推荐人客户号
        $recom_pcustID = isset($arg_array['referrer']) && is_numeric($arg_array['referrer']) ? $arg_array['referrer'] : null;

        //会员类型
        $custType = $arg_array['custType'];

        //会员来源
        $custSource = $arg_array['custSource'];

        //会员来源扩展
        $custSourceExt = isset($arg_array['custSourceExt'])&&!empty($arg_array['custSourceExt'])?$arg_array['custSourceExt']:null;

        //add by allen.qiang 20150429 TEA-FUN-1003-TEA-下午茶会员导入功能 start
        $custname = isset($arg_array['custname']) ? trim($arg_array['custname']) : null;
        $editor = isset($arg_array['editor']) ? trim($arg_array['editor']) : null;
        //add by allen.qiang 20150429 TEA-FUN-1003-TEA-下午茶会员导入功能 end


        try {

            //查询初始会员等级
            $rank_array = $custRank->getRankForNeedAmt( 0 );
            if (!$rank_array) {
                throw new Exception('会员数据未初始化', 404);
            }

            //检查会员并保存
            $cust_obj = new entity('cust_master');
            $cust_obj->custID = $custID;
            if ($G_SHOP->DBCA->fetch($cust_obj)) {
                throw new Exception('会员名已被使用，请使用其他会员名尝试注册', 404);
            }
            $cust_obj->creator = $custID;
            $cust_obj->pcustID = generate_seqno('seqno_customer');
            $cust_obj->nickName = $custID;
            $cust_obj->rankID = $rank_array['rankID'];
            $cust_obj->rankName = $rank_array['rankName'];
            $cust_obj->pwd = md5($pwd);
            $cust_obj->useFlg = 1;
            $cust_obj->head_pic = 'customer/default_user.gif';
            $cust_obj->unionName = $unionName;
            $cust_obj->nickName = $nickName;
            $cust_obj->mobile = encryptD($mobile);
            $cust_obj->recom_pcustID = $recom_pcustID;
            $cust_obj->sumAmt = 0;
            $cust_obj->custSource = $custSource;
            $cust_obj->custSource_ext = $custSourceExt;
            $cust_obj->custType = $custType;
            //add by allen.qiang 20150429 TEA-FUN-1003-TEA-下午茶会员导入功能 start
            $cust_obj->custname = encryptD($custname);
            $cust_obj->editor = $editor;
            //add by allen.qiang 20150429 TEA-FUN-1003-TEA-下午茶会员导入功能 end
            if (!$G_SHOP->DBCA->save($cust_obj)) {
                throw new Exception('页面已过期，请刷新页面重试', 404);
            }


            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            //加载会员促销类
            quanli_include('module/base/promotion/promotionCustomer.class.php');


            //实例会员促销类
            $promotionHandler = new promotionCustomer();


            //查询会员促销活动并发放
            $promotionHandler->grantCustPromotion( $cust_obj->pcustID, $custID, 1 );


            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            $result_array = array(
                'rankID' => $cust_obj->rankID,
                'rankName' => $cust_obj->rankName,
                'pcustID' => $cust_obj->pcustID,
                'custID' => $custID,
                'nickName' => $nickName,
                'email' => null,
                'custType' => $custType,
                'mobile' => $mobile,
                'custSource' => $custSource,
                'recom_pcustID' => $recom_pcustID,
                'register_time' => $G_SHOP->sys_datetime
            );

            //记录注册来源渠道
            $this->registerCustChannel($result_array);

            return array( 'code' => 200, 'message' => 'ok', 'data' => $result_array );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }
    /**
     * 注册会员渠道来源
     * @return bool
     */
    public function registerCustChannel($result_array){

        global $G_SHOP;
        /**
         * ==========================
         * 渠道会员
         * ==========================
         */
        $tracker_code = $G_SHOP->get_cookie_info('__etrack_tracker_code');
        $key1 = $G_SHOP->get_cookie_info('__etrack_key1');
        $key2 = $G_SHOP->get_cookie_info('__etrack_key2');
        $key3 = $G_SHOP->get_cookie_info('__etrack_key3');
        $referrer = $G_SHOP->get_cookie_info('__etrack_referrer');
        $referrer_time = $G_SHOP->get_cookie_info('__etrack_referrer_time');
        $tracker = $G_SHOP->get_cookie_info('__etrack');
        $tracker_array = explode('|', $tracker);
        $etrack_switch = $G_SHOP->get_cookie_info('__etrack_switch');

        $cityName = '';
        $city_id = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        if($city_id !== null){
            //获取城市名称
            $citySql = 'SELECT name FROM sys_region WHERE id = ' . intval($city_id);
            $cityRow = $G_SHOP->DBCA->stmt_query($citySql);
            $cityName = !empty($cityRow)?$cityRow[0]->name:'';
        }

        $cust_channel = new entity('cust_channel');
        $cust_channel->pcustID = $result_array['pcustID'];
        if (!$G_SHOP->DBCA->fetch($cust_channel)) {
            $cust_channel->creator = 'system';
            $cust_channel->source_url = $referrer;
            $cust_channel->source_time = $referrer_time;
            $cust_channel->key1 = $key1;
            $cust_channel->key2 = $key2;
            $cust_channel->key3 = $key3;
            $cust_channel->tracker_code = $tracker_code;
            $cust_channel->session_id = $tracker_array[0];
            $cust_channel->switch_id = $etrack_switch;
            $cust_channel->ip = get_ip();
            $cust_channel->source_channel = $_REQUEST['custSource'] == 1 ? 'web' : 'wap';
            $cust_channel->city_name = $cityName;
            $G_SHOP->DBCA->save( $cust_channel );
        }
        unset($G_SHOP);
    }

    /**
     * 用户前端登录信息设置
     * @param array $customer_array
     * @param int $guest //前台登录会员类型 1、未使用密码登录的会员 0、会员
     * @return bool
     */
    public function shopCheckin( $customer_array, $guest = 0 ) {

        global $G_SHOP;

        //登录记录
        $cust_login_log_obj = new entity('cust_login_log');
        $cust_login_log_obj->creator = 'system_auto';
        $cust_login_log_obj->pcustID = $customer_array['pcustID'];
        $cust_login_log_obj->IPPort = $G_SHOP->remoteIP . ':' . $G_SHOP->remotePort;
        $cust_login_log_obj->loginTime = $G_SHOP->sys_datetime;
        $cust_login_log_obj->client_side = isset($customer_array['client_side']) ? $customer_array['client_side'] : 'pc';
        $G_SHOP->DBCA->save($cust_login_log_obj);

        //添加SESSION
        if (!$login_session = $G_SHOP->sessionCache_get( 'LOGINSESSION' )) {
            $login_session = array();
        }

        $login_session['pcustID'] = $customer_array['pcustID'];
        $login_session['custID'] = $customer_array['custID'];
        $login_session['guest'] = $guest;
        $G_SHOP->sessionCache_set( 'LOGINSESSION', $login_session, G_LOGINSESSION_TIMEOUT );

        //查询会员最后一次购买记录
        $sess_log = $this->getBuyLog( $customer_array['pcustID'] );
        $G_SHOP->sessionCache_set( 'CUST_BUY_LOG', $sess_log, G_LOGINSESSION_TIMEOUT );

        return true;

    }

    /**
     * 修改会员信息
     * @param array $args_array 参数数组
     * @return array
     */
    public function editCustomer( $args_array ) {

        global $G_SHOP;

        //加载类文件
        quanli_include('module/base/system/sysRegion.class.php');
        quanli_include('module/base/customer/custRank.class.php');
        quanli_include('module/base/common/quanliFile.class.php');

        //实例地址类
        $sysRegion = new sysRegion( $G_SHOP->DBCA );

        //实例会员等级类
        $custRank = new custRank();

        //实例文件类
        $quanliFile = new quanliFile();


        //检查参数
        if (!isset($args_array['pcustID'], $args_array['operator']) || !quanli_is_int($args_array['pcustID'], 2) || empty($args_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if ($args_array['pcustID'] == 0 && ($args_array['custType'] == 1 || $args_array['custType'] == 2)  && (!isset($args_array['custID']) || !is_mobile($args_array['custID']))) {
            return array( 'code' => 400, 'message' => '会员名必须是手机号码' );
        }

        if (!isset($args_array['custSource']) || !in_array($args_array['custSource'], array(1, 2, 3, 4, 5, 6, 7))) {
            return array( 'code' => 400, 'message' => '请选择会员来源' );
        }

        if (!isset($args_array['custType']) || !in_array($args_array['custType'], array(1, 2, 3, 4))) {
            return array( 'code' => 400, 'message' => '请选择会员类型' );
        }

        if (!isset($args_array['nickName']) || empty($args_array['nickName'])) {
            return array( 'code' => 400, 'message' => '请输入会员昵称' );
        }

        if (!isset($args_array['custname']) || empty($args_array['custname'])) {
            return array( 'code' => 400, 'message' => '请输入会员姓名' );
        }

        if (!isset($args_array['phone'])) {
            $args_array['phone'] = null;
        } else if (!empty($args_array['phone']) && !is_phone($args_array['phone'])) {
            return array( 'code' => 400, 'message' => '固定电话格式错误' );
        }

        if ($args_array['custType'] != 4 && (!isset($args_array['mobile']) || !is_mobile($args_array['mobile']))) {
            return array( 'code' => 400, 'message' => '手机号码格式错误' );
        }

        if (!isset($args_array['email'])) {
            $args_array['email'] = null;
        } else if (!empty($args_array['email']) && !is_email($args_array['email'])) {
            return array( 'code' => 400, 'message' => '邮箱格式错误' );
        }

        if (!isset($arg_array['sexy']) || !in_array($arg_array['sexy'], array(1, 2, 3))) {
            $arg_array['sexy'] = 0;
        }

        if (!isset($args_array['birthday'])) {
            $args_array['birthday'] = null;
        } else if (!empty($args_array['birthday']) && !is_date($args_array['birthday'])) {
            return array( 'code' => 400, 'message' => '生日格式错误' );
        }

        if (!isset($args_array['provinceid']) || !quanli_is_int($args_array['provinceid'])) {
            $args_array['provinceid'] = 0;
            $args_array['cityid'] = 0;
            $args_array['countyid'] = 0;
        }
        if (!isset($args_array['cityid']) || !quanli_is_int($args_array['cityid'])) {
            $args_array['cityid'] = 0;
            $args_array['countyid'] = 0;
        }
        if (!isset($args_array['countyid']) || !quanli_is_int($args_array['countyid'])) {
            $args_array['countyid'] = 0;
        }

        if (!isset($args_array['address']) || empty($args_array['address'])) {
            $args_array['address'] = null;
        }

        if (!isset($args_array['maritalStatus']) || !in_array($args_array['maritalStatus'], array(0, 1, 2))) {
            $args_array['maritalStatus'] = 0;
        }

        if (!isset($args_array['monthlyIncome']) || !in_array($args_array['monthlyIncome'], array(0, 1, 2, 3, 4, 5))) {
            $args_array['monthlyIncome'] = 0;
        }

        if (!isset($args_array['head_pic']) || empty($args_array['head_pic'])) {
            $args_array['head_pic'] = 'customer/default_user.gif';
        } else {
            $args_array['head_pic'] = $quanliFile->basename_db($args_array['head_pic']);
            $arr = explode("/",$args_array['head_pic']);
            if($arr[count($arr)-1]=='default_user.gif'){
                $args_array['head_pic'] = 'customer/default_user.gif';
            }
        }

        try {

            //查询省份
            if ($args_array['provinceid'] > 0) {
                $region_array = array(
                    'id' => $args_array['provinceid'],
                    'region_level' => 1
                );
                $province_array = $sysRegion->getAreaManageList( $region_array );
            }

            //查询市区
            if ($args_array['cityid'] > 0) {
                $region_array = array(
                    'id' => $args_array['cityid'],
                    'parentID' => $args_array['provinceid'],
                    'region_level' => 2
                );
                $city_array = $sysRegion->getAreaManageList( $region_array );
            }

            //查询地区
            if ($args_array['countyid'] > 0) {
                $region_array = array(
                    'id' => $args_array['countyid'],
                    'parentID' => $args_array['cityid'],
                    'region_level' => 3
                );
                $county_array = $sysRegion->getAreaManageList( $region_array );
            }

            //新增、修改会员信息
            $cust_obj = new entity('cust_master');
            if ($args_array['pcustID'] > 0) { //修改

                $cust_obj->pcustID = $args_array['pcustID'];
                if (!$G_SHOP->DBCA->fetch($cust_obj)) {
                    throw new Exception('会员信息没有找到', 404);
                }

            } else { //新增

                $pwd = get_random_string(6);//随机生成的密码

                //检查会员是否存在
                $cust_obj->custID = $args_array['custID'];
                if ($G_SHOP->DBCA->fetch($cust_obj)) {
                    throw new Exception('会员名已存在，请使用其他会员名', 404);
                }

                //查询初始会员等级
                $rank_array = $custRank->getRankForNeedAmt( 0 );
                if (!$rank_array) {
                    throw new Exception('会员数据未初始化', 404);
                }

                $cust_obj->pcustID = generate_seqno('seqno_customer');
                $cust_obj->creator = $args_array['operator'];
                $cust_obj->sumAmt = 0;
                $cust_obj->rankID = $rank_array['rankID'];
                $cust_obj->rankName = $rank_array['rankName'];
                $cust_obj->useFlg = 1;
                $cust_obj->pwd = md5($pwd);

            }

            $cust_obj->nickName = $args_array['nickName'];
            $cust_obj->custname = encryptD($args_array['custname']);
            $cust_obj->sexy = $args_array['sexy'];
            $cust_obj->email = encryptD($args_array['email']);
            $cust_obj->birthday = $args_array['birthday'];
            $cust_obj->head_pic = $args_array['head_pic'];
            $cust_obj->mobile = encryptD($args_array['mobile']);
            $cust_obj->phone = encryptD($args_array['phone']);
            if (isset($province_array) && !empty($province_array)) {
                $cust_obj->provinceid = $province_array[0]['id'];
                $cust_obj->provinceName = $province_array[0]['name'];
            }
            if (isset($city_array) && !empty($city_array)) {
                $cust_obj->cityid = $city_array[0]['id'];
                $cust_obj->cityName = $city_array[0]['name'];
            }
            if (isset($county_array) && !empty($county_array)) {
                $cust_obj->countyid = $county_array[0]['id'];
                $cust_obj->countyName = $county_array[0]['name'];
            }
            $cust_obj->address = encryptD($args_array['address']);
            $cust_obj->custSource = $args_array['custSource'];
            $cust_obj->custType = $args_array['custType'];
            $cust_obj->maritalStatus = $args_array['maritalStatus'];
            $cust_obj->monthlyIncome = $args_array['monthlyIncome'];
            $cust_obj->isMobileVerify = 0;
            if (!$G_SHOP->DBCA->save($cust_obj)) {
                throw new Exception('页面已过期，请刷新页面重试', 406);
            }

            if (isset($pwd)) {

                /**
                 * =============================
                 * 检查会员促销活动
                 * =============================
                 */

                //加载会员促销类
                quanli_include('module/base/promotion/promotionCustomer.class.php');


                //实例会员促销类
                $promotionHandler = new promotionCustomer();


                //查询会员促销活动并发放
                $promotionHandler->grantCustPromotion( $cust_obj->pcustID, $cust_obj->custID, 1 );


                /**
                 * =============================
                 * 检查会员促销活动
                 * =============================
                 */

                $data_array = array(
                    'pwd' => $pwd,
                    'mobile' => $args_array['mobile'],
                    'custID' => $cust_obj->custID,
                    'pcustID' => $cust_obj->pcustID
                );
                return array( 'code' => 200, 'message' => '会员保存成功', 'data' => $data_array );
            } else {
                return array( 'code' => 200, 'message' => '会员保存成功' );
            }


        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 根据会员号得到会员等级信息
     * @param int $pcustID
     * @return array
     */
    public function getCustRank( $pcustID ) {

        global $G_SHOP;
        quanli_require('module/base/shop/shopCart.class.php');
        quanli_require('module/base/activity/activitySpike.class.php');

        $shopCart = new shopCart();
        $bill_array = $shopCart->getCartInfo('now_buy');
        $activityspike=new activitySpike();
        $isbool = false;
        if(isset($bill_array['master']['billPromotion']) && $bill_array['master']['billPromotion'] == $activityspike->billPromotion)//是否秒杀活动
            $isbool = true;

        

        if (!is_null($pcustID)) {

            //查询会员信息
            $cust_obj = new entity('cust_master');
            $cust_obj->pcustID = $pcustID;
            if ($G_SHOP->DBCA->fetch($cust_obj)) {

                //查询会员等级信息
                $rank_obj = new entity('cust_rank');
                $rank_obj->rankID =$isbool ? 1: $cust_obj->rankID;

                if ($G_SHOP->DBCA->fetch($rank_obj)) {

                    return array(
                        'rankID' => $rank_obj->rankID,
                        'rate' =>$isbool ? 1:$rank_obj->rate,
                        'pointsRate' => $rank_obj->pointsRate,
                        'freightFree' => $rank_obj->freightFree,
                    );

                }

            }

        }

        return array(
            'rankID' => 0,
            'rate' => 1,
            'pointsRate' => 1,
            'freightFree' => 1
        );

    }

    /**
     * 查询会员最后一次购买记录
     * @param int $pcustID 会员号
     * @return array
     */

    public function getBuyLog( $pcustID ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //SQL字段类型字符串
        $params_type = '';

        //SQL字段值数组
        $params_array = array();

        $item_array = array(
            'pcustID' => $pcustID,
            'deliverID' => 0,
            'send_region_id' => 0,
            'payTypeID' => 0,
            'pay_type' => 0,
            'payment_method_id' => 0,
            'invoiceID' => 0,
            'send_time_id' => 0,
            'extend_1' => 0,
            'extend_2' => 0,
            'extend_3' => 0,
            'extend_4' => 0,
            'extend_5' => 0,
            'extend_6' => 0
        );

        if (!isset($pcustID) || !is_numeric($pcustID))
            return $item_array;

        //客户号
        $sql .= ' WHERE pcustID = ?';
        $params_type .= 'i';
        $params_array[] = $pcustID;

        try {


            //查询分类信息
            $search_sql = 'SELECT * FROM bill_cust_buy_log ' . $sql;
            $temp_item_array = $G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return $item_array;

            $item_array = array(
                'pcustID' => $temp_item_array[0]->pcustID,
                'deliverID' => $temp_item_array[0]->deliverID,
                'send_region_id' => $temp_item_array[0]->send_region_id,
                'payTypeID' => $temp_item_array[0]->payTypeID,
                'pay_type' => $temp_item_array[0]->pay_type,
                'payment_method_id' => $temp_item_array[0]->payment_method_id,
                'invoiceID' => $temp_item_array[0]->invoiceID,
                'send_time_id' => $temp_item_array[0]->sendTimeID,
                'extend_1' => $temp_item_array[0]->extend_1,
                'extend_2' => $temp_item_array[0]->extend_2,
                'extend_3' => $temp_item_array[0]->extend_3,
                'extend_4' => $temp_item_array[0]->extend_4,
                'extend_5' => $temp_item_array[0]->extend_5,
                'extend_6' => $temp_item_array[0]->extend_6
            );


            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 会员重置密码
     * @param array $arg_array 参数数组
     * @return array
     * @throws Exception
     */
    public function resetCustPwd( $arg_array ) {

        global $G_SHOP;

        //检查参数
        if (!isset($arg_array['mobile'], $arg_array['new_pwd'], $arg_array['re_new_pwd'])) {
            return array('code' => 400, 'message' => '参数错误');
        }

        //新密码
        if (!is_pwd($arg_array['new_pwd']))
            return array('code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字或符号');

        //重复新密码
        if ($arg_array['new_pwd'] != $arg_array['re_new_pwd'])
            return array('code' => 400, 'message' => '您两次输入的密码不一致');

        $customer_obj = new entity('cust_master');
        $customer_obj->custID = $arg_array['mobile'];
        if (!$G_SHOP->DBCA->fetch($customer_obj)) {
            return array('code' => 404, 'message' => '会员信息没有找到');
        }
        $customer_obj->custType = 1;
        $customer_obj->pwd = md5($arg_array['new_pwd']);
        $G_SHOP->DBCA->save( $customer_obj );

        $result_array = array(
            'pcustID' => $customer_obj->pcustID,
            'custID' => $customer_obj->custID,
            'nickName' => $customer_obj->nickName,
            'custType' => $customer_obj->custType,
            'mobile' => $customer_obj->mobile,
            'recom_pcustID' => $customer_obj->recom_pcustID
        );
        return array( 'code' => 200, 'message' => '密码重置成功', 'data' => $result_array);

    }

    /**
     * 会员启用/禁用
     * @param array $args_array
     * @return array
     */
    public function changeCustomerUseFlg( $args_array ) {

        global $G_SHOP;

        if (!isset($args_array['pcustID'], $args_array['useFlg']) || !quanli_is_int($args_array['pcustID']) || !in_array($args_array['useFlg'], array(0, 1))) {
            return array( 'code' => 400, 'message' => '参数错误1' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //查询会员信息
            $cust_obj = new entity('cust_master');
            $cust_obj->pcustID = $args_array['pcustID'];
            if (!$G_SHOP->DBCA->fetch($cust_obj)) {
                throw new Exception('会员信息没有找到', 404);
            }
            if ($cust_obj->useFlg == 0 && $args_array['useFlg'] == 0) {
                throw new Exception('会员已禁用', 404);
            }
            if ($cust_obj->useFlg == 1 && $args_array['useFlg'] == 1) {
                throw new Exception('会员已启用', 404);
            }
            $cust_obj->useFlg = $args_array['useFlg'];
            $G_SHOP->DBCA->save($cust_obj);

            //日志类
            $quanliLog = new quanliLog();

            $log_array = array(
                'logItem' => $_REQUEST['pcustID'],
                'logCategoryID' => 9,
                'operator' => $G_SHOP->currentUserID,
                'extend_1' => $cust_obj->useFlg ? '会员启用' : '会员禁用'
            );
            $quanliLog->saveLogInfo( $log_array );

            $G_SHOP->DBCA->commit();

            if ($cust_obj->useFlg) {
                return array( 'code' => 200, 'message' => '会员启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '会员禁用成功' );
            }

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 修改会员密码
     * @param array $arg_array 参数数组
     * @return array
     * @throws Exception
     */
    public function editCustPwd( $arg_array ) {

        global $G_SHOP;

        //检查参数
        if (!isset( $arg_array['newPwd'], $arg_array['reNewPwd']))
            return array('code' => 400, 'message' => '参数错误');

        //旧密码
//        if (empty($arg_array['oldPwd']))
//            return array('code' => 400, 'message' => '请输入旧密码');

        //新密码
        if (!is_pwd($arg_array['newPwd']))
            return array('code' => 400, 'message' => '新密码必须是6-30位字符，可使用字母、数字或符号的组');

        //重复新密码
        if ($arg_array['newPwd'] != $arg_array['reNewPwd'])
            return array('code' => 400, 'message' => '两次填写的新密码不一致');

        try {


            $customer_obj = new entity('cust_master');
            $customer_obj->pcustID = $arg_array['pcustID'];
            if (!$G_SHOP->DBCA->fetch($customer_obj))
                throw new Exception('会员信息没有找到，请重新登录', 404);
//            if (strcasecmp($customer_obj->pwd, md5($arg_array['oldPwd'])) != 0)
//                throw new Exception('旧密码不正确，请重新输入', 406);
            $customer_obj->pwd = md5($arg_array['newPwd']);
            $G_SHOP->DBCA->save($customer_obj);

            return array( 'code' => 200, 'message' => '密码修改成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }
	/**
	 * 查询会员的提示信息
	 * @return array
	 */
    public function promptInfo($custID){
    	global $G_SHOP;
    	
    	$sql = '';
    	$params_type ='';
    	$sql.= 'AND custID = ?';
        $params_type .= 's';
        $params_array[] = $custID;
       
       
        $sql .= ' AND  start_time <= ?';
        $params_type .= 's';
        $params_array[] = $G_SHOP->sys_datetime;
       
        $sql .= ' AND  end_time >= ?';
        $params_type .= 's';
        $params_array[] =  $G_SHOP->sys_datetime;
        
        
        if ($sql) {
        	$sql = 'WHERE ' . substr($sql, 3);
        }
        $sql .= sprintf(' ORDER BY prompt_code desc');
        $search_sql = 'SELECT * FROM cust_prompt_info '.$sql ;
        $arr = $G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        $item_array = array();

        if($arr){
            foreach ($arr as &$item) {

                //用户信息数组
                $item_array[]  = array(
                    'info'	    => 	$item->info,

                );
            }
        }

        //add by 20141023 allen.qiang  lv5会员新加提示信息 ---start
        quanli_require('module/base/activity/activitySpike.class.php');
        //实例活动类
        $activityspike=new activitySpike();
        $sql_lv5="SELECT COUNT(*) AS item_count FROM cust_master WHERE custID =? AND rankID=5"; //判断是否是lv5 会员 查询语句
        $sql_lv5_count="SELECT count(1) AS item_count  FROM bill_master WHERE custID =?  AND bill_status <> 10 AND billPromotion = ?  AND createTime>? AND createTime<?"; //判断是否已使用LV5五折购特权 查询语句
        //参数类型字符串
        $params_type2 = '';
        //参数值数组
        $params_array2 = array();
        $params_type2 .= 's';
        $params_array2[] =$custID;

        $temp_item_array = &$G_SHOP->DBCA->stmt_query($sql_lv5,$params_type2,$params_array2);
        if($temp_item_array){
            $item_count = $temp_item_array[0]->item_count;
            if($item_count>0){ //是lv5 会员
                $params_type2 .= 's';
                $params_array2[] =$activityspike->billPromotion_lv5; //LV5会员五折购销渠道ID
                $params_type2 .= 's';
                $params_array2[] =date('Y')."-01-01 00:00:00";
                $params_type2 .= 's';
                $params_array2[] =date('Y')."-12-31 23:59:59";
                $temp_item_array2 = &$G_SHOP->DBCA->stmt_query($sql_lv5_count,$params_type2,$params_array2);
                if($temp_item_array2){
                    $item_count2 = $temp_item_array2[0]->item_count;
                    if ($item_count2 > 0) { //已使用过LV5五折购特权
                        $item_array[]  = array(
                            'info'	    => 	"该会员已使用过LV5五折购特权"
                        );
                    }else{  //未使用过LV5五折购特权
                        $item_array[]  = array(
                            'info'	    => 	"该会员可使用LV5五折购特权"
                        );
                    }
                }
            }
        }
        //add by 20141023 allen.qiang  lv5会员新加提示信息 ---end

        //add by 20141029 allen.qiang  农业银行信用卡五折购所剩蛋糕数量提示信息 ---start
            if(date('Y-m-d H:i:s')<date('Y-12-15 22:00:00')){
                $nh_xyk_num=$activityspike->nh_xyk_num400(); //农业银行信用卡五折购所剩蛋糕数量
                $item_array[]  = array(
                    'info'	    => 	"BD农行五折购还剩".$nh_xyk_num."个蛋糕"
                );
            }
        //add by 20141029 allen.qiang  农业银行信用卡五折购所剩蛋糕数量提示信息 ---end

        //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
//        quanli_require('module/base/activity/Yuan1.class.php');
//        //实例化"1元饼干"购买活动类
//        $activity_yuan1 = new Yuan1();
//        $_REQUEST["custID"]=$custID;
//        $result_array= $activity_yuan1->isCompetence($_REQUEST);
//        if($result_array["code"]==200){
//            $item_array[]  = array(
//                'info'	    => 	"该会员拥有“拿破仑Mini1元饼干”购买权限，只能购买一个，活动范围：仅上海所有免运费的区域"
//            );
//        }

        quanli_require('module/base/activity/Yuan9.class.php');
        //实例化"1元饼干"购买活动类
        $activity_yuan9 = new Yuan9();
        $_REQUEST["custID"]=$custID;
        $result_array9= $activity_yuan9->isCompetence($_REQUEST);
        if($result_array9["code"]==200){
            $item_array[]  = array(
                'info'	    => 	"该会员拥有“拿破仑Mini9.9元饼干”购买权限，只能购买一个，活动范围：仅上海所有免运费的区域"
            );
        }



        //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end

        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---start
        quanli_require('module/base/activity/activityCbc.class.php');
        //实例建设银行五折购活动类
        $activityCBC=new activityCbc();
        $_REQUEST["custID"]=$custID;
        $activity_master=$activityCBC->activity_master($_REQUEST);
        if($activity_master["isDate"]==1){
            $item_array[]  = array(
                'info'	    => 	"今日BD建设银行信用卡五折购蛋糕剩余".$activity_master["activity_num"]."个"
            );
            if($activity_master["activity_status"]==1){
                $item_array[]  = array(
                    'info'	    => 	"该用户今日已购买过建设银行信用卡五折购蛋糕"
                );
            }else{
                $item_array[]  = array(
                    'info'	    => 	"该用户今日未购买过建设银行信用卡五折购蛋糕"
                );
            }
        }

        //add by guojun.song 2015-04-29   MK-AC-1012-MCAKE-EC母亲节活动
        if(date('Y-m-d H:i:s') > '2015-04-30 10:00:00' && date('Y-m-d H:i:s') < '2015-05-15 23:59:59'){

            $maKaLong = $G_SHOP->DBCA->stmt_query("SELECT SUM(goods.goods_amount) AS num FROM bill_goods AS goods,bill_master AS bill WHERE goods.bill_no = bill.bill_no AND goods.product_code = 'X0502' AND bill.bill_status <> 10 AND bill.createTime > '2015-04-30 10:00:00'");

            $num_maKaLong = 0;

            $num_maKaLong += !is_null($maKaLong[0]->num)?intval($maKaLong[0]->num):0;

            $sum_maKaLong = 1990;

            $num_maKaLong = intval($sum_maKaLong - $num_maKaLong);

            $item_array[]  = array(
                'info'	    => 	"马卡龙蛋糕还剩{$num_maKaLong}个"
            );

        }

        //end by guojun.song 2015-04-29


        //add by haibin.miao 2015-05-25 start

        //$nextday = date('Y-m-d',strtotime("+1 day"));
        $today = date('Y-m-d');
        $starttime = $today.' 00:00:00';
        $endtime = $today.' 23:59:59';

        $sql = "SELECT uuid FROM bill_master WHERE billPromotion=509 AND bill_status<>10 AND createTime BETWEEN '".$starttime."' AND  '".$endtime."' AND custID=$custID";

        $result = $G_SHOP->DBCA->stmt_query($sql);

        if($result){

            $item_array[]  = array(
                'info'	    => 	"该会员今日已下过农行升磅蛋糕"
            );
        }

        //add by haibin.miao 2015-05-25 end



        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---end

    	return array( 'code' => 200, 'message' => '查询成功', 'data' => $item_array);
    	
    	
    }


    /**
     * 修改会员手机号码
     * @param array $arg_array 参数数组
     * @return array
     * @throws Exception
     */
    public function editCustMobile( $arg_array ) {

        global $G_SHOP;

        //检查参数
        if (!isset( $arg_array['mobile']))
            return array('code' => 400, 'message' => '参数错误');

        //登录密码
        if (!isset($arg_array['pwd']) || empty($arg_array['pwd']))
            return array('code' => 400, 'message' => '请输入登录密码');

        //新手机号码
        if (!is_mobile($arg_array['mobile']))
            return array('code' => 400, 'message' => '手机号码格式错误，请填写正确的手机号码');



        try {


            $customer_obj = new entity('cust_master');
            $customer_obj->pcustID = $arg_array['pcustID'];
            if (!$G_SHOP->DBCA->fetch($customer_obj))
                throw new Exception('会员信息没有找到，请重新登录', 404);

            if($customer_obj->pwd != md5($arg_array['pwd']))
                throw new Exception('会员登录密码不正确，请重新填写', 404);


            $customer_obj->mobile = encryptD($arg_array['mobile']);
            $G_SHOP->DBCA->save($customer_obj);

            return array( 'code' => 200, 'message' => '手机号码修改成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 优化会员等级逻辑
     * $rankID：会员等级ID
     * allen.qiang(allen.qiang@fistforward.com)
     * add by 20141104 allen.qiang 优化会员等级逻辑
     */
    public function getCustVipLevel($rankID)
    {
        if ($rankID == 1) {
            return 'vip1';
        } else if ($rankID ==2) {
            return 'vip2';
        } else if ($rankID ==3) {
            return 'vip3';
        } else if ($rankID ==4) {
            return 'vip4';
        } else if ($rankID ==5) {
            return 'vip5';;
        } else {
            return 'vip1';
        }

    }
}
